package com.myhouse.common.utils.myquartz.action;

import com.myhouse.common.exception.MyException;
import com.myhouse.common.utils.myquartz.entity.JobDetailAndTriggerPair;
import com.myhouse.common.utils.myquartz.factory.SchedulerFactory;
import org.quartz.*;

/**
 * scheduler实现类
 * @author 章瑜亮
 */
public class SchedulerAction implements SchedulerActionListener{
    /**
     * scheduler
     */
    private Scheduler scheduler;

    /**
     * 构造方法
     */
    public SchedulerAction() {
        this.scheduler = SchedulerFactory.getInstance();
    }

    /**
     * scheduler 部署
     * @param pair pair
     */
    @Override
    public SchedulerAction schedule(JobDetailAndTriggerPair pair) {
        try {
            this.scheduler.scheduleJob(pair.getJobDetail(), pair.getTriggeer());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return this;
    }

    /**
     * scheduler启动
     */
    @Override
    public void start() {
        if (this.scheduler == null) {
            throw new MyException("scheduler 未实例化");
        }
        try {
           this.scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * scheduler恢复
     * @param pair JobDetailAndTriggerPair
     */
    @Override
    public void resume(JobDetailAndTriggerPair pair) {
        if (this.scheduler == null) {
            throw new MyException("scheduler 未实例化");
        }
        JobDetail jobDetail = pair.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        Trigger trigger = pair.getTriggeer();
        TriggerKey triggerKey = trigger.getKey();
        try {
            this.scheduler.resumeJob(jobKey);
            this.scheduler.resumeTrigger(triggerKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * scheduler暂停
     * @param pair JobDetailAndTriggerPair
     */
    @Override
    public void pause(JobDetailAndTriggerPair pair) {
        if (this.scheduler == null) {
            throw new MyException("scheduler 未实例化");
        }
        JobDetail jobDetail = pair.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        Trigger trigger = pair.getTriggeer();
        TriggerKey triggerKey = trigger.getKey();
        try {
            this.scheduler.pauseJob(jobKey);
            this.scheduler.pauseTrigger(triggerKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * scheduler停止
     */
    @Override
    public void stop() {
        if (this.scheduler == null) {
            throw new MyException("scheduler 未实例化");
        }
        try {
            this.scheduler.clear();
            this.scheduler.shutdown();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
